package com.liyou.full.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @param exception
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){

        if (exception.getMessage().contains("Duplicate entry")) {
            String[] strings = exception.getMessage().split(" ");
            String message = "账号" + strings[2] + "已存在";
            return Result.error(message);
        }
        return Result.error("未知错误");

    }

    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException exception){
        log.error(exception.getMessage());
        return Result.error(exception.getMessage());
    }

}
